package com.xoa.service.hr.impl;

import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.hr.HrStaffInfoMapper;
import com.xoa.dao.hr.hrDispatcher.HrDispatcherMapper;
import com.xoa.dao.hr.hrPersonnelScheduling.HrPersonnelSchedulingMapper;
import com.xoa.dao.hr.hrPersonnelScheduling.HrShedulingLogMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.common.SysCode;
import com.xoa.model.department.Department;
import com.xoa.model.duties.UserPost;
import com.xoa.model.hr.HrStaffInfo;
import com.xoa.model.hr.HrStaffInfoExample;
import com.xoa.model.hr.HrStaffInfoWithBLOBs;
import com.xoa.model.hr.hrDispatcher.HrDispatcher;
import com.xoa.model.hr.hrDispatcher.HrDispatcherExample;
import com.xoa.model.hr.hrPersonnelScheduling.HrShedulingLog;
import com.xoa.model.position.UserJob;
import com.xoa.model.sms.SmsBody;
import com.xoa.model.users.Users;
import com.xoa.service.hr.hrPersonnelScheduling.HrPersonnelSchedulingService;
import com.xoa.service.sms.SmsService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;
import com.xoa.util.dataSource.ContextHolder;
import com.xoa.util.page.PageParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by liuqian on 2018/10/19.
 */
@Service
public class HrPersonnelSchedulingServiceImpl implements HrPersonnelSchedulingService {

    @Resource
    HrPersonnelSchedulingMapper hrPersonnelSchedulingMapper;

    @Resource
    HrShedulingLogMapper hrShedulingLogMapper;

    @Resource
    SysCodeMapper sysCodeMapper;

    @Resource
    DepartmentMapper departmentMapper;

    @Resource
    HrStaffInfoMapper hrStaffInfoMapper;

    @Resource
    SmsService smsService;

    @Autowired
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Resource
    UsersMapper usersMapper;
    @Autowired
    HrDispatcherMapper hrDispatcherMapper;
    @Override
    public ToJson<HrStaffInfo> queryPeopleSchedulingList(String userId, String deptId, Integer projectName, String workJob, Integer locationAddress, String position,Integer page,Integer pageSize,Boolean useFlag) {
        ToJson<HrStaffInfo> json = new ToJson<HrStaffInfo>();
        Map<String,Object> map = new HashMap<String,Object>();
        Map<String,Object> map1 = new HashMap<String,Object>();
        Integer pageNumber = 0;
        Integer totalNum = 0;
        if (page != null && !"".equals(page)){
            pageNumber = (page - 1)*pageSize;
        }
        map.put("pageNumber", pageNumber);
        map.put("pageSize", pageSize);
        try{
            if(userId!=null&&!"".equals(userId)){
                String[] userIdStr = userId.split(",");
                map.put("userId",userIdStr);
            }
            if(deptId!=null&&!"".equals(deptId)){
                if (!"0".equals(deptId)&&!"ALL_DEPT".equals(deptId)){
                    String[] deptIdStr = deptId.split(",");
                    map.put("deptId",deptIdStr);
                }
            }
            map.put("projectName",projectName);
            map.put("workJob",workJob);
            map.put("locationAddress",locationAddress);
            map.put("jobPosition",position);
            List<HrStaffInfo> hrStaffInfoList = hrPersonnelSchedulingMapper.queryPeopleSchedulingList(map);
            totalNum = hrPersonnelSchedulingMapper.queryPeopleSchedulingTotal(map);
            if(hrStaffInfoList.size()>0){
                for(HrStaffInfo hrStaffInfo:hrStaffInfoList){
                    if(!"".equals(hrStaffInfo.getProjectName())&&hrStaffInfo.getProjectName()!=null&&!"null".equals(hrStaffInfo.getProjectName())){
                        hrStaffInfo.setProjectNAME(sysCodeMapper.getCodeName(hrStaffInfo.getProjectName()));
                    }
                    if(!"".equals(hrStaffInfo.getLocationAddress())&&hrStaffInfo.getLocationAddress()!=null&&!"null".equals(hrStaffInfo.getLocationAddress())){
                        hrStaffInfo.setLocationAddressName(sysCodeMapper.getCodeName(hrStaffInfo.getLocationAddress()));
                    }
                    if(hrStaffInfo.getDeptId()!=null){
                        hrStaffInfo.setDeptName(departmentMapper.getDeptNameById(hrStaffInfo.getDeptId()));
                    }
                    /*if(!"".equals(hrStaffInfo.getWorkJob())&&hrStaffInfo.getWorkJob()!=null&&!"null".equals(hrStaffInfo.getWorkJob())){
                        SysCode sysCode = sysCodeMapper.getSingleCode("WORK_JOB",hrStaffInfo.getWorkJob());
                        if (sysCode!=null){
                            hrStaffInfo.setWorkJob(sysCode.getCodeName());
                        }
                    }*/
                    if(!"".equals(hrStaffInfo.getJobPosition())&&hrStaffInfo.getJobPosition()!=null&&!"null".equals(hrStaffInfo.getJobPosition())){
                        hrStaffInfo.setJobPositionStr(hrPersonnelSchedulingMapper.getUserPostName(Integer.valueOf(hrStaffInfo.getJobPosition())));
                    }
                    if(!"".equals(hrStaffInfo.getWorkJob())&&hrStaffInfo.getWorkJob()!=null&&!"null".equals(hrStaffInfo.getWorkJob())){
                        hrStaffInfo.setWorkJobStr(hrPersonnelSchedulingMapper.getUserJobName(Integer.valueOf(hrStaffInfo.getWorkJob())));
                    }
                }
                json.setTotleNum(totalNum);//数据总条数
                json.setObj(hrStaffInfoList);
                json.setMsg("ok");
            }else{
                json.setMsg("没有数据");
            }
        }catch (Exception e){
            json.setMsg("false");
            e.printStackTrace();
        }
        return json;
    }
    @Override
    public ToJson<HrDispatcher> selectHrDispatcherList(String userId, String deptId, Integer projectName, String workJob, Integer locationAddress, String position, Integer page, Integer pageSize, Boolean useFlag) {
        ToJson<HrDispatcher> json = new ToJson<HrDispatcher>();
        Map<String,Object> map = new HashMap<String,Object>();
        Integer pageNumber = 0;
        Integer totalNum = 0;
        if (page != null && !"".equals(page)){
            pageNumber = (page - 1)*pageSize;
        }
        map.put("pageNumber", pageNumber);
        map.put("pageSize", pageSize);
        try{
            if(userId!=null&&!"".equals(userId)){
                String[] userIdStr = userId.split(",");
                map.put("userId",userIdStr);
            }
            if(deptId!=null&&!"".equals(deptId)){
                if (!"0".equals(deptId)&&!"ALL_DEPT".equals(deptId)){
                    String[] deptIdStr = deptId.split(",");
                    map.put("deptId",deptIdStr);
                }
            }
            map.put("projectName",projectName);
            map.put("workJob",workJob);
            map.put("locationAddress",locationAddress);
            map.put("jobPosition",position);
            List<HrDispatcher> hrDispatchers = hrDispatcherMapper.selectHrDispatcherList(map);
            for (HrDispatcher hrDispatcher:hrDispatchers) {
                String creater = hrDispatcher.getCreater();
                Users users = usersMapper.getByUserId(creater);
                hrDispatcher.setCreaterName(users.getUserName());
            }
            totalNum = hrDispatcherMapper.selectHrDispatcherTotal(map);
            if(hrDispatchers.size()>0){
                json.setTotleNum(totalNum);
                json.setObj(hrDispatchers);
                json.setMsg("ok");
            }else{
                json.setMsg("没有数据");
            }
        }catch (Exception e){
            json.setMsg("false");
            e.printStackTrace();
        }
        return json;
    }

    @Override
    public ToJson<HrDispatcher> loadHrDispatcherPages(Integer page,Integer pageSize){
        ToJson<HrDispatcher> json = new ToJson<>();
        try {
            Map<String,Object> map = new HashMap<>();
            Integer pageNumber = 0;
            Integer totalNum = 0;
            if (page != null && !"".equals(page)){
                pageNumber = (page - 1)*pageSize;
            }
            map.put("pageNumber",pageNumber);
            map.put("pageSize",pageSize);
            List<HrDispatcher> hrDispatchers = hrDispatcherMapper.loadHrDispatcherPages(map);
            for (HrDispatcher hrDispatcher:hrDispatchers) {
                String creater = hrDispatcher.getCreater();
                Users users = usersMapper.getByUserId(creater);
                hrDispatcher.setCreaterName(users.getUserName());
            }
            totalNum = hrDispatcherMapper.loadHrDispatcherTotal();
            json.setFlag(0);
            json.setObj(hrDispatchers);
            json.setTotleNum(totalNum);
        }catch (Exception e){
            json.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return json;
    }

    @Override
    public ToJson<HrDispatcher> selectHrDispatcherDetail(String assessScore){
        ToJson<HrDispatcher> json = new ToJson<>();
        try{
            HrDispatcherExample hrDispatcherExample = new HrDispatcherExample();
            HrDispatcherExample.Criteria criteria = hrDispatcherExample.createCriteria();
            criteria.andAssessScoreEqualTo(assessScore);
            List<HrDispatcher> hrDispatchers = hrDispatcherMapper.selectByExampleWithBLOBs(hrDispatcherExample);
            for (HrDispatcher hrDispatcher:hrDispatchers) {
                String creater = hrDispatcher.getCreater();
                Users users = usersMapper.selectUserByUserId(creater);
                hrDispatcher.setCreaterName(users.getUserName());
            }
            json.setFlag(0);
            json.setObj(hrDispatchers);
        }catch(Exception e){
            json.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return json;
    };

    @Override
    public BaseWrapper insertHrShedulingLogList(String userId, String locationAddress, String projectName,String jobPosition,String workJob, String staffId, HttpServletRequest request,String assessScore,String assessment,Integer openShut) {
        BaseWrapper baseWrapper =new BaseWrapper();
        String sqlType = (String) request.getSession().getAttribute("loginDateSouse");
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionCookie);
        try{
            StringBuilder stringBuilder = new StringBuilder();
            if (userId!=null&&!"".equals(userId)){
                String[] userIdStr = userId.split(",");
                for (int i = 0; i <userIdStr.length ; i++) {
                    HrStaffInfoExample hrStaffInfoExample = new HrStaffInfoExample();
                    HrStaffInfoExample.Criteria criteria = hrStaffInfoExample.createCriteria();
                    criteria.andUserIdEqualTo(userIdStr[i]);
                    List<HrStaffInfoWithBLOBs> hrStaffInfoWithBLOBs = hrStaffInfoMapper.selectByExampleWithBLOBs(hrStaffInfoExample);
                    if (hrStaffInfoWithBLOBs!=null&&hrStaffInfoWithBLOBs.size()>0){
                        HrStaffInfo hrStaffInfo = hrStaffInfoWithBLOBs.get(0);
                        stringBuilder.append(hrStaffInfo.getStaffId());
                        stringBuilder.append(",");
                    }
                    Users users1 =  new Users();
                    users1.setUserId(userIdStr[i]);
                    if(workJob!=null&&!"".equals(workJob)){
                        users1.setJobId(Integer.valueOf(workJob));
                    }
                    usersMapper.updateByUserId(users1);
                }
            }
            HrStaffInfo hrStaffInfo = new HrStaffInfo();
            String s = stringBuilder.toString();
            int j = 0 ;
            if(s!=null&&!"".equals(s)){
                String[] staffIdStr =  s.split(",");
                Integer mark = 0;
                String str = hrDispatcherMapper.selectMaxAssessScore();
                if (str==null||"".equals(str)){
                    mark = 0;
                }else {
                    mark = Integer.parseInt(str) + 1;
                }
                for(int i=0;i<staffIdStr.length;i++){
                    hrStaffInfo.setStaffId(Integer.valueOf(staffIdStr[i]));
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String lastUpdateTime = format.format(new Date());
                    hrStaffInfo.setLastUpdateTime(lastUpdateTime);
                    if(locationAddress!=null&&!"".equals(locationAddress)){
                        hrStaffInfo.setLocationAddress(Integer.valueOf(locationAddress));
                    }
                    if(projectName!=null&&!"".equals(projectName)){
                        hrStaffInfo.setProjectName(Integer.valueOf(projectName));
                    }
                    if(jobPosition!=null&&!"".equals(jobPosition)){
                        hrStaffInfo.setJobPosition(jobPosition);
                    }
                    if(workJob!=null&&!"".equals(workJob)){
                        hrStaffInfo.setWorkJob(workJob);
                    }
                    j += hrStaffInfoMapper.updatePersonFile(hrStaffInfo);
                    if (j > 0){
                        //记录人员调度信息
                        insertHrDispatcher(users,Integer.parseInt(staffIdStr[i]),locationAddress,projectName,jobPosition,workJob,assessScore,assessment, mark.toString());
                        //事务提醒
                        if (openShut.equals(0)&&openShut==0){
                            continue;
                        }
                        if ((locationAddress!=null&&!"".equals(locationAddress))||(projectName!=null&&!"".equals(projectName))){
                            HrStaffInfo hrStaffInfo1 = hrStaffInfoMapper.selectStaffInfoById(Integer.parseInt(staffIdStr[i]));
                            String userId1 = hrStaffInfo1.getUserId();
                            this.addAffairs(users,Integer.valueOf(staffIdStr[i]),userId1,"0",sqlType);
                        }
                    }
                }
            }
            if(j>0){
                baseWrapper.setFlag(true);
            }else{
                baseWrapper.setFlag(false);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return baseWrapper;
    }

    public Integer insertHrDispatcher(Users users,Integer staffId,String locationAddress, String projectName,String jobPosition,String workJob,String assessScore,String assessment,String mark){
        HrDispatcher hrDispatcher = new HrDispatcher();
        //考核分数assessScore
        if (assessScore!=null&&!"".equals(assessScore)){
            hrDispatcher.setAssessScore(assessScore);
        }
        //考核评价assessment
        if (assessment!=null&&!"".equals(assessment)){
            hrDispatcher.setAssessment(assessment);
        }
        //创建人
        String creater = users.getUserId();
        hrDispatcher.setCreater(creater);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createrTime = format.format(new Date());
        //创建时间
        hrDispatcher.setCreaterTime(createrTime);
        //最后修改时间
        hrDispatcher.setUpdateTime(createrTime);
        HrStaffInfo hrStaffInfo = hrStaffInfoMapper.selectStaffInfoById(staffId);
        //被调度人ID
        String userId = hrStaffInfo.getUserId();
        hrDispatcher.setUserId(userId);
        //被调度人名称
        String userName = hrStaffInfo.getStaffName();
        hrDispatcher.setUserName(userName);
        //被调度人部门ID
        Integer deptId = hrStaffInfo.getDeptId();
        hrDispatcher.setDeptId(deptId);
        //被调度人部门名称
        Department department = departmentMapper.selectByDeptId(deptId);
        if (department!=null) {
            hrDispatcher.setDeptName(department.getDeptName());
        }
        //被调度人历史信息
        HrDispatcherExample hrDispatcherExample = new HrDispatcherExample();
        hrDispatcherExample.setOrderByClause("DISPATCHER_ID DESC");
        HrDispatcherExample.Criteria criteria = hrDispatcherExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        List<HrDispatcher> hrDispatchers = hrDispatcherMapper.selectByExampleWithBLOBs(hrDispatcherExample);
        int size = hrDispatchers.size();
        //职务jobPosition
        if(jobPosition!=null&&!"".equals(jobPosition)){
            int jobPositionId = Integer.parseInt(jobPosition);
            hrDispatcher.setJobPositionId(jobPositionId);
            //得到职务
            String userPostName = hrPersonnelSchedulingMapper.getUserPostName(jobPositionId);
//            String codeName = sysCodeMapper.getCodeName(jobPositionId);
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < size; i++) {
                HrDispatcher info = hrDispatchers.get(i);
                String jobPositionName = info.getJobPositionName();
                if (jobPositionName!=null&&!"".equals(jobPositionName)){
                    int indexOf = jobPositionName.indexOf(",");
                    if (indexOf>0){
                        String substring = jobPositionName.substring(indexOf + 1);
                        stringBuilder.append(substring);
                    }else {
                        stringBuilder.append(jobPositionName);
                    }
                    stringBuilder.append(",");
                    break;
                }
            }
            stringBuilder.append(userPostName);
            hrDispatcher.setJobPositionName(stringBuilder.toString());
        }
        //项目projectName
        if(projectName!=null&&!"".equals(projectName)){
            int projectId = Integer.parseInt(projectName);
            hrDispatcher.setProjectId(projectId);
            //得到项目
            String codeName = sysCodeMapper.getCodeName(projectId);
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < size; i++) {
                HrDispatcher info = hrDispatchers.get(i);
                String projectName1 = info.getProjectName();
                if (projectName1!=null&&!"".equals(projectName1)){
                    int indexOf = projectName1.indexOf(",");
                    if (indexOf>0){
                        String substring = projectName1.substring(indexOf + 1);
                        stringBuilder.append(substring);
                    }else {
                        stringBuilder.append(projectName1);
                    }
                    stringBuilder.append(",");
                    break;
                }
            }
            stringBuilder.append(codeName);
            hrDispatcher.setProjectName(stringBuilder.toString());
        }
        //岗位workJob
        if(workJob!=null&&!"".equals(workJob)){
            int workJobId = Integer.parseInt(workJob);
            hrDispatcher.setWorkJobId(workJobId);
            //得到岗位
            String userJobName = hrPersonnelSchedulingMapper.getUserJobName(workJobId);
//            String codeName = sysCodeMapper.getCodeName(workJobId);
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < size; i++) {
                HrDispatcher info = hrDispatchers.get(i);
                String workJobName = info.getWorkJobName();
                if (workJobName!=null&&!"".equals(workJobName)){
                    int indexOf = workJobName.indexOf(",");
                    if (indexOf>0){
                        String substring = workJobName.substring(indexOf + 1);
                        stringBuilder.append(substring);
                    }else {
                        stringBuilder.append(workJobName);
                    }
                    stringBuilder.append(",");
                    break;
                }
            }
            stringBuilder.append(userJobName);
            hrDispatcher.setWorkJobName(stringBuilder.toString());
        }
        //所在位置locationAddress
        if(locationAddress!=null&&!"".equals(locationAddress)){
            int locationAddressId = Integer.parseInt(locationAddress);
            hrDispatcher.setLocationAddressId(locationAddressId);
            String codeName = sysCodeMapper.getCodeName(locationAddressId);
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < size; i++) {
                HrDispatcher info = hrDispatchers.get(i);
                String locationAddressName = info.getLocationAddressName();
                if (locationAddressName!=null&&!"".equals(locationAddressName)){
                    int indexOf = locationAddressName.indexOf(",");
                    if (indexOf>0){
                        String substring = locationAddressName.substring(indexOf + 1);
                        stringBuilder.append(substring);
                    }else {
                        stringBuilder.append(locationAddressName);
                    }
                    stringBuilder.append(",");
                    break;
                }
            }
            stringBuilder.append(codeName);
            hrDispatcher.setLocationAddressName(stringBuilder.toString());
        }
        Integer num;
        hrDispatcher.setAssessScore(mark);
        num = hrDispatcherMapper.insertSelective(hrDispatcher);
        return num;
    }

    @Async
    public void addAffairs(final Users users,final Integer staffId,final String toIds,final String isAttach,final String sqlType) {
        this.threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                SmsBody smsBody = new SmsBody();
                //发送人ID
                smsBody.setFromId(users.getUserId());
                smsBody.setContent("人员调度通知" );
                //发送时间
                long nowTime = System.currentTimeMillis()/1000;
                Integer nowTimeInt = new Long(nowTime).intValue();
                smsBody.setSendTime(nowTimeInt);
                //提示类型
                SysCode sysCode = new SysCode();
                sysCode.setCodeName("人员调度");
                sysCode.setParentNo("SMS_REMIND");
                SysCode codeNoByNameAndParentNo = sysCodeMapper.getCodeNoByNameAndParentNo(sysCode);
                if (codeNoByNameAndParentNo != null) {
                    smsBody.setSmsType(codeNoByNameAndParentNo.getCodeNo());
                }
                //是否有附件
                smsBody.setIsAttach(isAttach);
                //跳转链接
                smsBody.setRemindUrl("/hrPersonnelScheduling/details?staffId=" + staffId);
                String title = "";
                String context = "";
                smsService.saveSms(smsBody, toIds, "1", "1", title, context, sqlType);
            }
        });
    }

    @Override
    public ToJson<HrShedulingLog> queryHrShedulingLogList(String projectName,String address,String dispatcher,String userId,Integer page,Integer pageSize,Boolean useFlag) {
        ToJson<HrShedulingLog> json = new ToJson<HrShedulingLog>();
        try{
            Map<String,Object>map = new HashMap<String,Object>();
            PageParams pageParams = new PageParams(); //分页
            pageParams.setPage(page);
            pageParams.setPageSize(pageSize);
            pageParams.setUseFlag(useFlag);
            map.put("page", pageParams);
            map.put("projectName",projectName);
            map.put("address",address);
            map.put("dispatcher",dispatcher);
            map.put("userId",userId);
            hrShedulingLogMapper.queryHrShedulingLogList(map);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }



    @Override
    public BaseWrapper queryHrShedulingLogList(String projectName) {
        BaseWrapper baseWrapper = new BaseWrapper();
        try{
            List<Map<String,Object>>list = new ArrayList<Map<String,Object>>();
            Map<String,Object>mapResult = new HashMap<String,Object>();
            //根据所在位置分组
            List<SysCode> sysCodes  = sysCodeMapper.getSysCode("LOCATION_ADDRESS");
            Map<String,Object>map = new HashMap<String,Object>();
            map.put("projectName",projectName);
            for(SysCode sysCode:sysCodes){
                map.put("address", sysCode.getCodeId());
                Integer i = hrPersonnelSchedulingMapper.queryHrShedulingLogList(map);
                if(i==null){
                    mapResult.put(sysCode.getCodeName(),0);
                }else{
                    mapResult.put(sysCode.getCodeName(),i);
                }
            }
            list.add(mapResult);
            baseWrapper.setData(list);
        }catch (Exception e){
            e.printStackTrace();
        }
        return baseWrapper;
    }

    @Override
    public BaseWrapper queryPostSchedulingStatistics() {
        BaseWrapper baseWrapper = new BaseWrapper();
        try{
            List<Map<String,Object>>list = new ArrayList<Map<String,Object>>();
            Map<String,Object>mapResult = new HashMap<String,Object>();
            //根据所在位置分组
            List<SysCode> sysCodes  = sysCodeMapper.getSysCode("WORK_JOB");
            Map<String,Object>map = new HashMap<String,Object>();
            for(SysCode sysCode:sysCodes){
                map.put("workJob", sysCode.getCodeId());
                Integer i = hrPersonnelSchedulingMapper.queryPostSchedulingStatistics(map);
                if(i==null){
                    mapResult.put(sysCode.getCodeName(),0);
                }else{
                    mapResult.put(sysCode.getCodeName(),i);
                }


            }
            list.add(mapResult);
            baseWrapper.setData(list);
        }catch (Exception e){
            e.printStackTrace();
        }
        return baseWrapper;
    }
    @Override
    public ToJson hrStaffInfo(Integer staffId) {
        ToJson toJson = new ToJson();
        try {
            if (staffId != null){
                HrStaffInfoWithBLOBs hrStaffInfoWithBLOBs = hrStaffInfoMapper.selectAllById(staffId);
                if (hrStaffInfoWithBLOBs != null){
                    //项目名称
                    Integer projectName = hrStaffInfoWithBLOBs.getProjectName();
                    String codeName = sysCodeMapper.getCodeName(projectName);
                    hrStaffInfoWithBLOBs.setProjectNAME(codeName);
                    //项目地址
                    Integer locationAddress = hrStaffInfoWithBLOBs.getLocationAddress();
                    String codeName1 = sysCodeMapper.getCodeName(locationAddress);
                    hrStaffInfoWithBLOBs.setLocationAddressName(codeName1);
                    //发布人
                    String createUserId = hrStaffInfoWithBLOBs.getCreateUserId();
                    List<Users> users = usersMapper.selectListByUserId(createUserId);
                    hrStaffInfoWithBLOBs.setCreateName(users.get(0).getUserName());
                    //发布人部门
                    Integer createDeptId = hrStaffInfoWithBLOBs.getCreateDeptId();
                    Department department = departmentMapper.selectByDeptId(createDeptId);
                    hrStaffInfoWithBLOBs.setDeptName(department.getDeptName());
                    //岗位
                    Integer workJob = Integer.parseInt(hrStaffInfoWithBLOBs.getWorkJob());
                    String codeName2 = sysCodeMapper.getCodeName(workJob);
                    hrStaffInfoWithBLOBs.setWorkJobStr(codeName2);
                    //职务
                    Integer jobPosition = Integer.parseInt(hrStaffInfoWithBLOBs.getJobPosition());
                    String codeName3 = sysCodeMapper.getCodeName(jobPosition);
                    hrStaffInfoWithBLOBs.setJobPositionStr(codeName3);
                    toJson.setObject(hrStaffInfoWithBLOBs);
                    toJson.setFlag(0);
                }else {
                    toJson.setMsg("没有数据");
                }
            }else {
                toJson.setMsg("ID为空");
            }
        } catch (Exception e) {
            toJson.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return toJson;
    }

    @Override
    public ToJson<HrDispatcher> selectHrDispatcherDetails(Integer staffId,String userId){
        ToJson<HrDispatcher> json = new ToJson<>();
        try{
            if (userId!=null&&!"".equals(userId)&&staffId!=null){
                HrDispatcherExample hrDispatcherExample = new HrDispatcherExample();
                hrDispatcherExample.setOrderByClause("DISPATCHER_ID DESC");
                HrDispatcherExample.Criteria criteria = hrDispatcherExample.createCriteria();
                criteria.andUserIdEqualTo(userId);
                List<HrDispatcher> hrDispatchers = hrDispatcherMapper.selectByExampleWithBLOBs(hrDispatcherExample);
                for (HrDispatcher hrDispatcher:hrDispatchers) {
                    String creater = hrDispatcher.getCreater();
                    Users users = usersMapper.selectUserByUserId(creater);
                    hrDispatcher.setCreaterName(users.getUserName());
                }
                HrStaffInfoWithBLOBs hrStaffInfoWithBLOBs = hrStaffInfoMapper.selectAllById(staffId);
                //部门名称
                Integer deptId = hrStaffInfoWithBLOBs.getDeptId();
                if(deptId!=null){
                    Department department = departmentMapper.selectByDeptId(deptId);
                    hrStaffInfoWithBLOBs.setDeptName(department.getDeptName());
                }
                //职务
                String jobPosition = hrStaffInfoWithBLOBs.getJobPosition();
                if (jobPosition!=null&&!"".equals(jobPosition)){
//                    String codeName = sysCodeMapper.getCodeName(Integer.parseInt(jobPosition));
                    String userPostName = hrPersonnelSchedulingMapper.getUserPostName(Integer.parseInt(jobPosition));
                    hrStaffInfoWithBLOBs.setJobPositionStr(userPostName);
                }
                //岗位
                String workJob = hrStaffInfoWithBLOBs.getWorkJob();
                if (workJob!=null&&!"".equals(workJob)){
//                    String codeName = sysCodeMapper.getCodeName(Integer.parseInt(workJob));
                    String userJobName = hrPersonnelSchedulingMapper.getUserJobName(Integer.parseInt(workJob));
                    hrStaffInfoWithBLOBs.setWorkJobStr(userJobName);
                }
                //项目
                Integer projectName = hrStaffInfoWithBLOBs.getProjectName();
                if (projectName!=null){
                    String codeName = sysCodeMapper.getCodeName(projectName);
                    hrStaffInfoWithBLOBs.setProjectNAME(codeName);
                }
                //所在位置
                Integer locationAddress = hrStaffInfoWithBLOBs.getLocationAddress();
                if (locationAddress!=null){
                    String codeName = sysCodeMapper.getCodeName(locationAddress);
                    hrStaffInfoWithBLOBs.setLocationAddressName(codeName);
                }
                json.setObj(hrDispatchers);
                json.setObject(hrStaffInfoWithBLOBs);
                json.setFlag(0);
            }else {
                json.setMsg("参数错误");
            }
        }catch (Exception e){
            json.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return json;
    }

    @Override
    public ToJson<List<Map<String,Object>>> hrStaffInfoStatistical(String projectName,String locationAddress){
        ToJson<List<Map<String,Object>>> toJson = new ToJson<>();
        List<Map<String,Object>> list = new ArrayList<>();
        List listObj = new ArrayList();
        Map<String,Object> map = new HashMap<>();
        map.put("projectName",projectName);
        map.put("locationAddress",locationAddress);
        //职务
//        List<SysCode> jobPositionSysCode  = sysCodeMapper.getSysCode("JOB_POSITION");
        List<UserPost> userPost = hrPersonnelSchedulingMapper.getUserPost();
        //岗位
//        List<SysCode> workJobSysCode  = sysCodeMapper.getSysCode("WORK_JOB");
        List<UserJob> userJob = hrPersonnelSchedulingMapper.getUserJob();
        //项目
        List<SysCode> projectNameSysCode  = sysCodeMapper.getSysCode("PROJECT_NAME");
        //所在位置
        List<SysCode> locationAddressSysCode  = sysCodeMapper.getSysCode("LOCATION_ADDRESS");
        try {
            //项目
            if ("".equals(projectName)||projectName==null){
                Integer projectName1 = select(list, projectNameSysCode, map, "projectName");
                listObj.add("项目总人数："+projectName1);
            }
            //所在位置
            if ("".equals(locationAddress)||locationAddress==null){
                Integer locationAddress1 = select(list, locationAddressSysCode, map, "locationAddress");
                listObj.add("所在位置总人数："+locationAddress1);
            }
            //职务
            Integer jobPosition = selectUserPost(list, userPost, map, "jobPosition");
            listObj.add("职务总人数："+jobPosition);
            //岗位
            Integer workJob = selectUserJob(list, userJob, map, "workJob");
            listObj.add("岗位总人数："+workJob);
            toJson.setFlag(0);
            toJson.setObject(list);
            toJson.setObj(listObj);
        }catch (Exception e){
            toJson.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return toJson;
    }

    public Integer selectUserJob(List<Map<String,Object>> list,List<UserJob> userJobs,Map map,String s){
        Integer number = 0;
        Map<String,Object> maps = new HashMap<>();
        for (UserJob userJob:userJobs) {
            Integer jobId = userJob.getJobId();
            String jobName = userJob.getJobName();
            map.put(s, jobId);
            Integer i = hrPersonnelSchedulingMapper.hrStaffInfoStatistical(map);
            number += i;
            maps.put(jobName,i);
            map.remove(s);
        }
        list.add(maps);
        return number;
    }

    public Integer selectUserPost(List<Map<String,Object>> list,List<UserPost> userPosts,Map map,String s){
        Integer number = 0;
        Map<String,Object> maps = new HashMap<>();
        for (UserPost userPost:userPosts) {
            Integer postId = userPost.getPostId();
            String postName = userPost.getPostName();
            map.put(s, postId);
            Integer i = hrPersonnelSchedulingMapper.hrStaffInfoStatistical(map);
            number += i;
            maps.put(postName,i);
            map.remove(s);
        }
        list.add(maps);
        return number;
    }

    public Integer select(List<Map<String,Object>> list,List<SysCode> sysCodes,Map map,String s){
        Integer number = 0;
        Map<String,Object> maps = new HashMap<>();
        for (SysCode sysCode:sysCodes) {
            Integer codeId = sysCode.getCodeId();
            String codeName = sysCode.getCodeName();
            map.put(s, codeId);
            Integer i = hrPersonnelSchedulingMapper.hrStaffInfoStatistical(map);
            number += i;
            maps.put(codeName,i);
            map.remove(s);
        }
        list.add(maps);
        return number;
    }

    @Override
    public ToJson<UserPost> getUserPost(){
        ToJson<UserPost> toJson = new ToJson<>();
        try {
            List<UserPost> userPost = hrPersonnelSchedulingMapper.getUserPost();
            toJson.setObj(userPost);
            toJson.setFlag(0);
        }catch (Exception e){
            toJson.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return toJson;
    }

    @Override
    public ToJson<UserJob> getUserJob(){
        ToJson<UserJob> toJson = new ToJson<>();
        try {
            List<UserJob> userJob = hrPersonnelSchedulingMapper.getUserJob();
            toJson.setObj(userJob);
            toJson.setFlag(0);
        }catch (Exception e){
            toJson.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return toJson;
    }
}
